package com.star.percalservice.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.star.percalservice.mapper.PaperMapper;
import com.star.percalservice.mapper.TeacherMapper;
import com.star.percalservice.mapper.UserMapper;
import com.star.percalservice.model.dto.PaperDTO;
import com.star.percalservice.model.entity.Paper;
import com.star.percalservice.model.entity.ResearchProject;
import com.star.percalservice.model.entity.Teacher;
import com.star.percalservice.model.entity.User;
import com.star.percalservice.model.vo.PaperVO;
import com.star.percalservice.model.vo.ProjectVO;
import com.star.percalservice.service.PaperService;
import com.star.percalservice.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class PaperServiceImpl implements PaperService {

    @Autowired
    private PaperMapper paperMapper;
    @Autowired
    private TeacherMapper teacherMapper;
    @Autowired
    private UserMapper userMapper;

    @Override
    public R list(PaperDTO paperDTO) {
        List<Paper> list = paperMapper.list(paperDTO);
        List<PaperVO> resList = new ArrayList<>();
        list.forEach(paper -> {
            PaperVO paperVO = new PaperVO();
            paperVO.setPaper(paper);
            Teacher teacher = teacherMapper.selectById(paper.getTeacherId());
            User user = userMapper.selectById(teacher.getUserId());
            paperVO.setTeacherName(user.getRealName());
            resList.add(paperVO);
        });
        return R.ok("查询成功", resList);
    }

    @Override
    public R add(Paper paper) {
        QueryWrapper<Paper> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("title", paper.getTitle());
        if (ObjectUtil.isNotNull(paperMapper.selectOne(queryWrapper))) {
            return R.error("论文名称已存在");
        }
        return paperMapper.insert(paper) > 0 ? R.ok("添加成功") : R.error("添加失败");
    }

    @Override
    public R update(Paper paper) {
        return paperMapper.updateById(paper) > 0 ? R.ok("修改成功") : R.error("修改失败");
    }

    @Override
    public R delete(Integer id) {
        return paperMapper.deleteById(id) > 0 ? R.ok("删除成功") : R.error("删除失败");
    }
}
